
function LgFileUp(d) {
    $.ajax({
        url: d.url,
        type: "POST",
        data: d.data,                    /**
                    *必须false才会自动加上正确的Content-Type                    */
        contentType: false,                    /**
                    * 必须false才会避开jQuery对 formdata 的默认处理
                    * XMLHttpRequest会对 formdata 进行正确的处理                    */
        processData: false,
        dataType: "json",
        success: function (data) {
            if (typeof (d.callback) == "function") {
                d.callback(true, data);
            }
        },
        error: function (err) {
            d.callback(false, err.responseText)
            // alert("上传失败！");
            //  $("#imgWait").hide();
        }
    });
}
function LoadFile(url) {
    if (layer != undefined) {
       var box=layer.open({
            type: 2,
            title: '下载处理中....',
            closeBtn: 0, //不显示关闭按钮
            shade: [0],
            area: ['300px', '200px'],
            time:30000,
            content: [url, 'no'] //iframe的url，no代表不显示滚动条
            , btn: ['下载已完成', '取消下载'] //只是为了演示
            , yes: function () {
                layer.close(box);
            }
            , btn2: function () {
                layer.close(box);
            }
        });
    } else {
        console.error("下载脚本依赖layer插件，请先加载layer插件库!")
    }
}
function Area() {
    this.province = "";
    this.city = "";
    this.district = "";
    this.addr = "";
    this.target = null;
    this.name = "";
    this.formVal = "";
    this.textValide = 0;
}
Area.prototype.getFullName = function () {
    var text = "";
    if (this.province != undefined && this.province != "") {
        text += this.province;
        if (this.city != undefined && this.city != "") {
            text += "/" + this.city;
            if (this.district != undefined && this.district != "") {
                text += "/" + this.district;
            }
        }
    }
    if (this.addr != undefined && this.addr != "") {
        text += "~" + this.addr
    }
    return text;
}
Area.prototype.setDataFromOptin = function () {
    this.province = $(this.target).find("select.province option:selected").text();
    this.city = $(this.target).find("select.city option:selected").text();
    this.district = $(this.target).find("select.district option:selected").text();
    this.addr = $(this.target).find("input.lg-area-text").val();
    this.autoSetFormData();
}
Area.prototype.autoSetFormData = function () {
    var value = this.getFullName();
    $(this.target).siblings("input[name=" + this.name + "]").val(value).blur();
}
Area.prototype.formatFormVal = function () {
    var i = this.formVal.indexOf("~");
    var arr = [];
    if (i > -1) {
        this.addr = this.formVal.substring(i + 1)
        arr = this.formVal.substring(0, i).split("/");;  
    } else {
        arr = this.formVal.split("/");       
    }
    if (arr.length >= 1) {
        this.province = arr[0]
    }
    if (arr.length >= 2) {
        this.city = arr[1]
    }
    if (arr.length == 3) {
        this.district = arr[2]
    }
}
var CityMap = {
    config: {
        areas: [],
        url: "",
        onFormChange: null,
        onSelect: null
    },
    Init: function (d) {
        //初始化数据,隐藏原input框并获取参数和数据，封装在area中，如果文本框中有数据则将其拆分给省市区，详细地址对应属性存储
        //数据初始化完成后，添加事件兼听
        if (d.areas != undefined && d.areas != null && d.areas.length > 0) { this.config.areas = d.areas };
        if (d.url != undefined && d.url != null && d.url != "") { this.config.url = d.url };
        if (d.onFormChange != undefined && d.onFormChange != null && typeof (d.onFormChange) == "function") { this.config.onFormChange = d.onFormChange };
        if (d.onSelect != undefined && d.onSelect != null && typeof (d.onSelect) == "function") { this.config.onSelect = d.onSelect }
        var that = this;
        $(".lg-form-area").each(function () {
            var name = $(this).attr("name");
            var val = $(this).val();
            var valide = $(this).data("valide")
            $(this).hide().after("<div data-name=\"" + name + "\" class=\"lg-inline selectBox citymap\"></div>");
            var area = new Area();
            area.name = name;
            area.formVal = val;
            area.textValide = valide;
            area.target = $(this).next(".citymap");
            if (val != undefined && val != null && val != "") {
                area.formatFormVal();
            }
            that.config.areas.push(area);
        })
        this.InitEvent();
    },
    InitEvent: function () {
        var that = this;
        $(document).ready(function () {
            $(".lg-form").on("change", ".lg-area-select", function (e) {
                var box = $(this).parent(".selectItem");
                var depth = parseInt($(this).data("depth"));
                box.nextAll().remove();
                var id = $(this).find("option:selected").val();
                if (id == "") {
                    return;
                }
                var text = $(this).find("option:selected").text();
                that.RenderViewData(box.parent(".citymap").data("name"));
                AjaxData({
                    url: that.config.url,
                    type: "get",
                    data: { psn: id },
                    callback: function (b, d) {
                        if (d.code == 0 && d.data != null && d.data.length > 0) {
                            that.Append(depth, d.data, box)
                        } else {
                            that.Append(3, null, box)
                        }
                    }
                })
            })
            $(".lg-form").on("keyup blur change", "input.lg-area-text", function (e) {
                var box = $(this).parent(".selectItem");
                that.RenderViewData(box.parent(".citymap").data("name"));
            })
            $(".lg-form").on("keydown", "input.lg-form-area", function (e) {
                return false;
            });
            $(".lg-form").on("focus", "input.lg-form-area", function (e) {
                $(this).siblings(".citymap").show().removeClass("hide");
            })
        })


    },
    render: function () {
        var that = this;
        this.GetData({
            psn: 0,
            callback: function (b, d) {
                if (d.code == 0) {
                    var html = "<div class=\"lg-form-inline selectItem\">"
                    html += "<select class=\"lg-select city-select province lg-form-reg lg-area-select\" data-reg=\"required\" data-depth=\"1\">"
                    html += "<option value=\"\">=====请选择省=====</option>"
                    for (var i in d.data) {
                        html += "<option class=\"insert\" value=\"" + d.data[i].SN + "\">" + d.data[i].Description + "</option>"
                    }
                    html += "</select>"
                    html += "</div>"
                    $(".citymap").each(function () {
                        $(this).append(html)
                    })
                    that.renderProvince();
                }
            }
        })
    },
    renderProvince: function () {
        var that = this;
        for (var i = 0; i < this.config.areas.length; i++) {
            var area = this.config.areas[i];
            if (area.province != "") {
                $(area.target).find("select.province option").each(function () {
                    if ($(this).text() == area.province) {
                        $(this).prop("selected", true);
                        if (area.city != "") {
                            that.renderCity(area, $(this).val());
                        }
                    }
                })
            }
        }
    },
    renderCity: function (area, psn) {
        var that = this;
        that.GetData({
            psn: psn,
            callback: function (b, d) {
                if (b) {
                    if (d.code == 0) {
                        var sn = null;
                        var data=d.data
                        html = "<div class=\"lg-form-inline selectItem\" >";
                        html += "<select class=\"lg-select city-select city lg-form-reg lg-area-select\" data-reg=\"required\" data-depth=\"2\">";
                        html += "<option value=\"\">=====请选择城市=====</option>";
                        for (var i in data) {
                            if (area.city == data[i].Description) {
                                sn = data[i].SN;
                                html += "<option class=\"insert\" selected=\"selected\" value=\"" + data[i].SN + "\">" + data[i].Description + "</option>";
                            } else {
                                html += "<option class=\"insert\" value=\"" + data[i].SN + "\">" + data[i].Description + "</option>";
                            }
                        }
                        html += "</select>";
                        html += "</div>";
                        $(area.target).append(html);
                        if (area.district != "") {
                            that.renderDistrict(area, sn)
                        }
                    }
                }
            }
        })
    },
    renderDistrict: function (area,psn) {
        var that = this;
        that.GetData({
            psn: psn,
            callback: function (b, d) {
                if (b) {
                    if (d.code == 0) {
                        var data = d.data
                        html = "<div class=\"lg-form-inline selectItem\" >";
                        html += "<select class=\"lg-select city-select district lg-form-reg lg-area-select\" data-reg=\"required\" data-depth=\"3\">";
                        html += "<option value=\"\">=====请选择县区=====</option>";
                        for (var i in data) {
                            if (area.district == data[i].Description) {
                               
                                html += "<option class=\"insert\" selected=\"selected\" value=\"" + data[i].SN + "\">" + data[i].Description + "</option>";
                            } else {
                                html += "<option class=\"insert\" value=\"" + data[i].SN + "\">" + data[i].Description + "</option>";
                            }
                        }
                        html += "</select>";
                        html += "</div>";
                        $(area.target).append(html);
                        if (area.addr != "") {
                            that.renderAddr(area)
                        }
                    }
                }
            }
        })
    },
    renderAddr: function (area) {
        if (area.textValide == 1) {
            html = "<div class=\"lg-form-inline selectItem\">"
            html += "<input type=\"text\" class=\"lg-type-text lg-input lg-area-text\" placeholder=\"请填写详细地址\" value=\"" + area.addr + "\">"
            html += "</div>"
            $(area.target).append(html);
        } else if (area.textValide == 2) {
            html = "<div class=\"lg-form-inline selectItem\">"
            html += "<input type=\"text\" class=\"lg-type-text lg-input lg-area-text lg-form-reg\" data-reg=\"required\" placeholder=\"请填写详细地址\" value=\"" + area.addr + "\">"
            html += "</div>"
            $(area.target).append(html);
        }
    },
    GetData: function (d) {
        $.ajax({
            //要用post方式      
            type: "get",
            //方法所在页面和方法名      
            url: this.config.url,
            // contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: { psn: d.psn },
            beforeSend: function () {
                if (typeof (d.beforeSend) == "function") {
                    d.beforeSend();
                }
            },
            success: function (data) {
                if (typeof (d.callback == "function")) {
                    d.callback(true, data)
                }
            },
            error: function (err) {
                if (typeof (d.callback == "function")) {
                    d.callback(false, err.responseText)
                }
            }
        });
    },
    Append: function (depth, data, target) {
        var html = "";
        switch (depth) {
            case 1:
                html = "<div class=\"lg-form-inline selectItem\" >"
                html += "<select class=\"lg-select city-select city lg-form-reg lg-area-select\" data-reg=\"required\" data-depth=\"2\">"
                html += "<option value=\"\">=====请选择城市=====</option>"
                for (var i in data) {
                    html += "<option class=\"insert\" value=\"" + data[i].SN + "\">" + data[i].Description + "</option>"
                }
                html += "</select>"
                html += "</div>"
                break;
            case 2:
                html = "<div class=\"lg-form-inline selectItem\">"
                html += "<select class=\"lg-select city-select district lg-form-reg lg-area-select\" data-reg=\"required\" data-depth=\"3\">"
                html += "<option value=\"\">=====请选择县区=====</option>"
                for (var i in data) {
                    html += "<option class=\"insert\" value=\"" + data[i].SN + "\">" + data[i].Description + "</option>"
                }
                html += "</select>"
                html += "</div>"
                break;
            case 3:
                //html = "<div class=\"lg-form-inline selectItem\">"
                //html += "<input type=\"text\" class=\"lg-type-text lg-input lg-area-text\" placeholder=\"请填写详细地址\">"
                //html += "</div>"
                break;
        }
        target.after(html)
    },
    DateToForm: function () {
        for (var i = 0; i < this.config.areas.length; i++) {
            var area = this.config.areas[i];
            area.autoSetFormData();
        }
    },
    RenderViewData: function (name) {
        for (var i = 0; i < this.config.areas.length; i++) {
            var area = this.config.areas[i];
            if (area.name == name) {
                area.setDataFromOptin();
                if (typeof (this.config.onFormChange) == "function") {
                    this.config.onFormChange(area);
                }
            }
        }
    },
    SetAreaData: function (arr) {
        
    },
}
function loadUeditor(e) {
    ue = UE.getEditor('editor', {
        toolbars: [
            [
                //'anchor', //锚点
                // 'undo', //撤销
                // 'redo', //重做
                'source', //源代码
                'bold', //加粗
                'italic', //斜体
                'underline', //下划线
                'strikethrough', //删除线
                'subscript', //下标
                // 'fontborder', //字符边框
                'superscript', //上标
                //  'formatmatch', //格式刷

                'blockquote', //引用
                'pasteplain', //纯文本粘贴模式
                //   'selectall', //全选
                //    'print', //打印
                'preview', //预览
                'horizontal', //分隔线
                'removeformat', //清除格式
                'indent', //首行缩进
                'justifyleft', //居左对齐
                'justifyright', //居右对齐
                'justifycenter', //居中对齐
                'justifyjustify', //两端对齐
                'forecolor', //字体颜色
                'backcolor', //背景色
                'insertorderedlist', //有序列表
                'insertunorderedlist', //无序列表
                //   'time', //时间
                // 'date', //日期

                //   'insertrow', //前插入行
                //  'insertcol', //前插入列
                //   'mergeright', //右合并单元格
                //    'mergedown', //下合并单元格
                //     'devarerow', //删除行
                //    'devarecol', //删除列
                //     'splittorows', //拆分成行
                //     'splittocols', //拆分成列
                //     'splittocells', //完全拆分单元格
                //    'devarecaption', //删除表格标题
                //     'inserttitle', //插入标题
                //     'mergecells', //合并多个单元格
                //       'devaretable', //删除表格
                //       'cleardoc', //清空文档
                //       'insertparagraphbeforetable', //"表格前插入行"
                'snapscreen', //截图
                'scrawl', //涂鸦
                'insertcode', //代码语言
                'fontfamily', //字体
                'fontsize', //字号
                'paragraph', //段落格式

                'simpleupload', //单图上传
                'insertimage', //多图上传
                'insertvideo', //视频
                'music', //音乐
                'attachment', //附件
                //   'edittable', //表格属性
                //   'edittd', //单元格属性
                'link', //超链接
                'unlink', //取消链接
                'emotion', //表情
                'spechars', //特殊字符
                //   'searchreplace', //查询替换
                //    'map', //Baidu地图
                //     'gmap', //Google地图  
                //    'help', //帮助
                'fullscreen', //全屏
                //   'directionalityltr', //从左向右输入
                //    'directionalityrtl', //从右向左输入
                //    'rowspacingtop', //段前距
                //    'rowspacingbottom', //段后距
                //     'pagebreak', //分页
                //    'insertframe', //插入Iframe
                //       'imagenone', //默认
                //       'imageleft', //左浮动
                //     'imageright', //右浮动 
                //      'imagecenter', //居中
                //      'wordimage', //图片转存
                //       'lineheight', //行间距
                //      'edittip ', //编辑提示
                //       'customstyle', //自定义标题
                //      'autotypeset', //自动排版
                //       'webapp', //百度应用
                //        'touppercase', //字母大写
                //       'tolowercase', //字母小写
                //        'background', //背景
                //         'template', //模板
                'inserttable', //插入表格
                //           'drafts', // 从草稿箱加载
                //         'charts', // 图表
            ]
        ]
    });
}
//延迟加载
var lazyLoad = {
    lazyParam: {
        where: {},
        page: 0,//页码
        limit: 15,//每页数量
        cols: 4,//列数
        state: true,
        loadtype: "button"
    },
    lazyInit: function (d) {
        //初始化参数
        if (d != undefined) {
            this.lazyParam.where = d.where;
            this.lazyParam.limit = d.limit;
            this.lazyParam.cols = d.cols;
            this.lazyParam.loadtype = d.loadtype;
        }
        //渲染容器
        for (i = 0; i < this.lazyParam.cols; i++) {
            $(".lazyLoad").append("<ul class=\"lazywrap\"></ul>");
        }
        //获取第一页数据
        this.initEvent();
        this.getData();

    },
    initEvent: function () {
        var that = this;
        if (this.lazyParam.loadtype == "scroll") {
            $(window).bind("scroll", function () {
                if (that.lazyParam.state) {
                    var wh = $(window).height();
                    var st = $(window).scrollTop();
                    var bh = $(document).height();
                    if ((bh - st - wh) < 200) {
                        that.getData();
                    }
                }
            });
        } else if (this.lazyParam.loadtype == "scroll") {
            $(".lazyLoad .load").unbind("click").bind("click", function () {
                if (this.lazyParam.state) {
                    that.getData();
                }
            })
        }
    },
    getData: function () {
        var that = this;
        this.lazyParam.state = false;
        var data = this.lazyParam.where;
        data.page = this.lazyParam.page + 1;
        data.limit = this.lazyParam.limit;
        AjaxData({
            url: "/api/UserDataHandler.ashx",
            type: "get",
            data: data,
            callback: function (b, d) {
                if (b) {
                    if (d.code == 0 && d.data.length > 0) {//有数据才插入
                        that.lazyParam.page++;
                        for (i = 0; i < d.data.length; i++) {
                            var min = $(".lazyLoad ul").eq(0).innerHeight(); var index = 0
                            $(".lazyLoad ul").each(function () {
                                if ($(this).innerHeight() < min) {
                                    min = $(this).innerHeight();
                                    index = $(this).index();
                                }
                            })
                            var li = "<li class=\"loading\">" +
                                "<div class=\"img\"><img src=\"" + d.data[i].ImageUrl + "\"></div>" +
                                "<span class=\"fa fa-calendar\"> " + d.data[i].AddTime.replace(/(\w.+)T(\w.+)(\.\w.+)?/g, "$1") + "</span>" +
                                "<a href=\"" + d.data[i].LinkUrl + "\" class=\"tittle\">" + d.data[i].Title + "</a></li>"
                            $(".lazyLoad ul").eq(index).append(li);
                        }
                        that.lazyParam.state = true;
                    } else {
                        alert("没有更多的数据了！");
                    }

                }
            }
        })
    }
}
//像册
var Photos = {
    params: {
        "imgs": [],
        "btPrev": ".btn-PicLeft",
        "btNext": ".btn-PicRight",
        "splitKey": "|",
        "step": 126
    },
    init: function (d) {
        this.params.splitKey = d.splitKey;
        this.params.imgs = d.imgs.split(this.params.splitKey);
        this.params.step = d.step;
        this.render();
        this.initEvent();
    },
    render: function () {
        var html = "<div class=\"PictureShowBox LgPhotos\" style=\"display: block; \">" +
            "<div class=\"PictureShow\">" +
            "<span class=\"close fa fa-window-close-o\" onclick=\"$('.LgPhotos').remove();\"></span>" +
            "<div class=\"PicShow\"><img src=\"\" alt=\"\" title=\"\"></div>" +
            "<div class=\"PicList\">" +
            "<ul style=\"margin-top:0px;\">";
        for (i = 0; i < this.params.imgs.length; i++) {
            html += "<li class=\"pic\"><img src=\"" + this.params.imgs[i] + "\"></li>"
        }
        html += "</ul></div><div class=\"c-b\"></div>" +
            "<span class=\"btn-PicLeft fa fa-angle-up\"></span>" +
            "<span class=\"btn-PicRight fa fa-angle-down\"></span>" +
            "</div></div>";
        $("body").append(html);
        $(".PicList ul li").eq(0).addClass("act").click();
    },
    initEvent: function () {
        var maxIndex = $(".LgPhotos .pic").length - 1;
        var step = this.params.step;
        var ul = $(".LgPhotos .PicList ul");
        ///前一个滚动事件
        $(this.params.btPrev).unbind().bind("click", function () {
            ul.css('marginTop', -step);
            ul.find("li").eq(maxIndex).prependTo(ul);
            ul.find("li").eq(1).click();
            ul.animate({ marginTop: "0px" }, 300);
        })
        //下一个滚动事件
        $(this.params.btNext).unbind().bind("click", function () {
            ul.animate({ marginTop: -step }, 300, function () {
                ul.find("li").eq(0).appendTo(ul);
                ul.find("li").eq(1).click();
                ul.css({ marginTop: "0px" });
            })
        })

        $(".LgPhotos .pic").unbind().bind("click", function () {
            $(this).addClass("act");
            $(".LgPhotos .PicShow img").attr("src", $(this).attr("src"));
        })
    }
}

/*自定义表单事件 */
var LgTable = {
    config: new Array(),
    render: function (d) {
        this.config = d;
        if (this.config.data != undefined && this.config.data.length > 0) {
            for (i = 0; i < this.config.data.length; i++) {
                this.config.data[i].index = i;
            }
        }
        this.init();
    },
    push: function (d) {
        var data = d.data;
        if (data != null && data != "" && data != undefined) {
            var tr = "<tr>"
            tr += "<td>" + data[i].PriceTitle + "</td>";
            tr += "<td>" + data[i].Price + "</td>";
            tr += "<td>" + data[i].MinAge + "</td>";
            tr += "<td>" + data[i].MaxAge + "</td>"
            tr += "</tr>"
            $(d.target).append(tr);
        }
    },
    init: function () {
        // alert(JSON.stringify(this.config.cols));
        //先清空表数据
        $(this.config.target).html("");
        //公参
        var cols = this.config.cols;
        var html = "";
        //渲染表头
        html = "<thead><tr>";
        for (var i = 0; i < cols.length; i++) {
            var align = cols[i].align == undefined ? "" : "align=\"" + cols[i].align + "\"";
            html += "<th " + align + " width=\"" + cols[i].width + "\">" + cols[i].title + "</th>"
        }
        html += "</tr></thead>"
        $(this.config.target).append(html);
        html = "";
        //判断是否有列的配置数据，有的话，开始渲染
        if (this.config.cols != undefined && this.config.cols.length > 0) {
            //渲染数据
            if (this.config.data != undefined && this.config.data.length > 0) {
                var data = this.config.data;
                $(this.config.target).append("<tbody>")
                for (var j = 0; j < data.length; j++) {
                    html = "<tr>"
                    for (var k = 0; k < cols.length; k++) {
                        var _cols = cols[k];//获取其中一列 josn对像
                        switch (_cols.type) {
                            case "index"://索引列
                                html += "<td class=\"td" + (k + 1) + "\">";
                                if (_cols.tempvar != undefined && typeof (_cols.tempvar) == "function") {
                                    html += _cols.tempvar(data[j]);
                                } else {
                                    html += (j + 1);
                                }
                                html += "</td>";
                                break;
                            case "field":
                                html += "<td class=\"td" + (k + 1) + "\">";
                                if (_cols.tempvar != undefined && typeof (_cols.tempvar) == "function") {
                                    html += _cols.tempvar(data[j]);
                                } else {
                                    html += data[j][_cols.field];
                                }
                                html += "</td>";
                                break
                            case "toolbar":
                                html += "<td>";
                                if (_cols.tempvar != undefined && typeof (_cols.tempvar) == "function") {
                                    html += _cols.tempvar(data[j]);
                                } else {
                                    html += $(_cols.toolbar).html();
                                }
                                html += "</td>";
                                break;
                        }
                    }
                    html += "</tr>";
                    $(this.config.target).append(html);
                    html = "";
                }
                $(this.config.target).append("</tbody>")
            } else {
                $(this.config.target).append("<tbody><tr class=\"nodata\"><td colspan=\"" + cols.length + "\">没有数据</td></tr></tbody>")
            }
        }
    },
    //删除一行数据后返回新的数据集合
    del: function (index) {
        var target = this.config.target;
        var data = this.config.data;
        //$(target).find("tr").eq(index).remove();
        var _data = [];
        for (i = 0; i < data.length; i++) {
            if (i != index) {
                _data.push(data[i])
            }
        }
        return _data;
    },
    edit: function (d) {

    },
    getTableData: function () {
        var data = new Array();
        var target = this.config.target;
        var cols = this.config.cols;
        $(target).find("tbody tr").each(function () {
            var hr = ""
            for (var i = 0; i < cols.length; i++) {
                var _cols = cols[i]
                if (_cols.type == "field") {
                    hr += ",\"" + _cols.field + "\":\"" + $(this).find("td").eq(i).text() + "\"";
                }
            }
            hr = hr.replace(',', '');
            hr = "{" + hr + "}";
            data.push(JSON.parse(hr));
        })
        return data;
    },
    initTr: function (data) {
        var cols = this.config.cols
        html = "<tr>"
        for (var i = 0; i < cols.length; i++) {
            var _cols = cols[i];//获取其中一列 josn对像
            if (_cols.type == "field") {//类型为字段列
                if (_cols.tempvar != undefined && typeof (_cols.typeof) == "function") {
                    html += "<td>" + _cols.tempvar(data) + "</td>";
                } else {
                    html += "<td>" + data[_cols.field] + "</td>"
                }
            } else if (_cols.type = "toolbar") {
                html += "<td>" + $(_cols.toolbar).html() + "</td>"
            }
        }
        html += "</tr>";
        return html;
    },
    getLineFormData: function (t) {
        var data = {}
        t.find(".lg-form").each(function () {
            var type = $(this).data("formtype");
            var key = $(this).attr("name");
            switch (type) {
                case "text":
                    data[key] = $(this).val();
                    break;
                case "select":
                    data[key] = $(this).find("option:selected").val();
                    break;
            }
        })
        return data;
    },
    getLineDataAndCheck: function (t) {
        var data = {}
        var errcount = 0;
        t.find(".lg-form").each(function () {
            var type = $(this).data("formtype");
            var key = $(this).attr("name");
            var reg = $(this).data("reg") == undefined ? "" : $(this).data("reg");
            var msg = $(this).data("errmsg") == undefined ? "" : $(this).data("errmsg");
            switch (type) {
                case "text":
                    data[key] = $(this).val() + "";
                    break;
                case "select":
                    data[key] = $(this).find("option:selected").val() + "";
                    break;
            }
            if (reg != undefined && reg != "") {
                var b = LgRegx.test({
                    "reg": reg + "",
                    "msg": msg + "",
                    "val": data[key] + ""
                })
                console.log(JSON.stringify({
                    "reg": reg + "",
                    "msg": msg + "",
                    "val": data[key] + ""
                }))
                if (!b.state) {
                    top.layer.msg(b.msg, { icon: 2 })
                    $(this).addClass("reg-error");
                    errcount++;
                    return false

                } else {
                    $(this).removeClass("reg-error");
                }
            }

        })
        if (errcount > 0) {
            return false;
        }
        return data;
    }
}

var editor = {
    singleRender: function (name) {
        UE.getEditor(name);
    },
    moreRender: function (names) {
        for (i = 0; i < names.length; i++) {
            UE.delEditor(names[i]);
            UE.getEditor(names[i])
        }
    },
    render: function (name) {
        UE.delEditor(name);
        UE.getEditor(name)
    },
    reRender: function (name) {
        UE.delEditor(name);
        $("#" + name).attr("style", "height:400px")
    }
}

function LgPager(d) {
    var target = "#LgPager";
    var step = 5;
    var callback = function () { };
    //初始化参数
    if (d.target != undefined && d.target != "") {
        target = d.target;
    }
    if (d.callback != undefined && typeof (d.callback == "funcation")) {
        callback = d.callback
    }
    if (d.step != undefined && d.step > 0) {
        step = d.step;
    }
    //分页对像
    var pager = {
        param: {
            target: target,
            callback: callback,
            step: step
        },
        init: function () {
            var that = this;
            $(function () {
                $(that.param.target).on("click", "a", function () {
                    console.log($(this).data("n"));
                    that.param.callback($(this).data("n"))
                })
            })
        },
        GetPagerCode: function (p) {
            //参数初始化
            var pagecount = 1;
            var step = this.param.step;
            var target = this.param.target;
            var callback = this.param.callback
            var starpage = 1;
            var endpage = 5;
            if (p.count > p.limit) {
                pagecount = p.count % p.limit > 0 ? parseInt(p.count / p.limit) + 1 : parseInt(p.count / p.limit);//页码总数
            }
            if (pagecount <= 5 || p.page <= 3) {
                endpage = pagecount > 5 ? 5 : pagecount;
            } else if (p.page <= pagecount - 2) {
                starpage = p.page - 2;
                endpage = p.page + 2;
            } else {
                starpage = pagecount - 4;
                endpage = pagecount;
            }
            var html = "<div>" +
                "<a href=\"javascript:;\" data-n=\"1\">首页</a>" +
                "<a href=\"javascript:;\" data-n=\"" + (p.page > 1 ? (p.page - 1) : 1) + "\" class=\"fa fa-angle-left lgpager-prev\"></a>";
            for (var i = starpage; i <= endpage; i++) {
                if (i == p.page) {
                    html += "<span class=\"act\">" + i + "</span>"
                } else {
                    html += "<a href=\"javascript:;\" data-n=\"" + i + "\">" + i + "</a>";
                }
            }
            html += "<a href=\"javascript:;\" data-n=\"" + (p.page < pagecount ? (p.page + 1) : pagecount) + "\" class=\"fa fa-angle-right lgpager-next\"></a>" +
                "<a href=\"javascript:;\" data-n=\"" + pagecount + "\">尾页</a>";

            html += "<span class=\"lgpager-jump\"><label>转到</label><input name=\"goPage\" /><button>go</button>" +
                "<span class=\"lgpager-count\">共" + p.count + "条</span>" +
                "<span class=\"lgpager-limit\"><select><option>10</option><option>20</option><option>30</option><option>50</option><option>100</option></select></span>"
            html += "</div>";
            $(this.param.target).html(html);
            return html;
        }
    }
    return pager;
}

var LgSlide = {
    param: {
        box: ".banner",
        item: ".img",
        btPrev: ".btPrev",
        btNext: ".btNext",
        btIndex: ".btIndex",
        timeStep: 3000,
        width: "100%",
        height: "auto",
        stoper: ".banner"
    },
    init: function (d) {
        //初始化参数
        for (var key in this.param) {
            if (d[key] != undefined && d[key] != "") {
                this.param[key] = d[key];
            }
        }
        this.render();
    },
    render: function () {
        var length = $(this.param.item).length;
        $(this.param.item).css({ "width": this.param.width })
        $(this.param.box).css({ "width": this.param.width * length + "px" });
        this.regevent();

    },
    regevent: function () {
        var that = this;
        var timer = setInterval(function () { that.play(-1) }, that.param.timeStep);
        $(this.param.stoper).bind("mouseover", function () {
            clearInterval(timer);
        }).bind("mouseout", function () {
            timer = setInterval(function () { that.play(-1) }, that.param.timeStep);
        })
        $(this.param.btNext).unbind().bind("click", function () {
            that.play(1);
        })

        $(this.param.btPrev).unbind().bind("click", function () {
            that.play(-1);
        })
    },
    play: function (i) {
        var box = $(this.param.box);
        var item = $(this.param.item)
        var w = this.param.width;
        //获取当前act类的图片容器下标，无则给第一个容器添加act
        if (i > 0) {
            box.animate({ marginLeft: -w }, 300, function () {
                item.eq(0).appendTo(box);
                box.css({ marginLeft: "0px" });
            });
        } else {
            box.css('marginLeft', -w);
            item.eq(item.length - 1).prependTo(box);
            box.animate({ marginLeft: "0px" }, 300);
        }
    }
}

var lg = {
    dom: function (selector) {
        this.selector = selector;
    },
    $: function (name, data) {
        var obj = this[name];
        if (obj && typeof obj == 'function') {
            return new obj(data);
        } else {
            console.error('['+name+']'+'不是个有效的可实例对像！')
        }
    },
    age: {
        getFullAge: function (idCard) {
            var myDate = new Date();
            var month = myDate.getMonth() + 1;
            var day = myDate.getDate();
            var age = myDate.getFullYear() - idCard.substring(6, 10) - 1;
            if (idCard.substring(10, 12) < month || idCard.substring(10, 12) == month && idCard.substring(12, 14) <= day) {
                age++;
            }
            return age;
        },
        getBirthday: function (idCard) {
            return idCard.substring(6, 10) + "-" + idCard.substring(10, 12) + "-" + idCard.substring(12, 14);
        }
    },
    log: {
        level: 1,
        debug: function (msg) {
            if (this.level > 0) {
                console.log(msg)
            }
        },
        error: function (msg) {
            if (this.level > 1) {
                console.error(msg)
            }
        }
    },
    request: function (d) {
        $.ajax({
            //要用post方式      
            type: d.method ? d.method:"get",
            //方法所在页面和方法名      
            url: d.url,
            //contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: d.data,
            beforeSend: function () {
                if (d.before != undefined&& typeof (d.before) == "function") {
                    d.before();
                }
            },
            success: function (data) {
                if (d.success != undefined && typeof(d.succss == "function")) {
                    d.success(data)
                }
            },
            error: function (err) {
                if (d.fail != undefined &&typeof(d.fail == "function")) {
                    d.fail(err.responseText)
                }
            },
            complete: function (data) {
                if (d.complete != undefined &&typeof(d.complete == "function")) {
                    d.complete(data);
                }
            }
        });
    },
    postFile: function (d) {
        $.ajax({
            //要用post方式      
            type:"post",
            //方法所在页面和方法名      
            url: d.url,
            contentType: false,                    /**
                    * 必须false才会避开jQuery对 formdata 的默认处理
                    * XMLHttpRequest会对 formdata 进行正确的处理                    */
            processData: false,
            dataType: "json",
            data: d.data,
            beforeSend: function () {
                if (d.before != undefined && typeof (d.before) == "function") {
                    d.before();
                }
            },
            success: function (data,status,xhr) {
                if (d.success != undefined && typeof (d.succss == "function")) {
                    d.success(data,status,xhr)
                }
            },
            error: function (err) {
                if (d.fail != undefined && typeof (d.fail == "function")) {
                    d.fail(err.responseText)
                }
            },
            complete: function (data) {
                if (d.complete != undefined && typeof (d.complete == "function")) {
                    d.complete(data);
                }
            }
        });
    },
    getFile: function (d) {
        var box = layer.load(2);
        var param = null;
        if (d.data) {
            param = new FormData();
            for (let key in d.data) {
                param.append(key,d.data[key])
            }
        }
        var xhr = new XMLHttpRequest();
        xhr.open("post", d.url);
        xhr.responseType = "blob";
        xhr.send(param);
        xhr.onload = function () {
            layer.close(box)
            console.log(xhr);
            if (xhr.status == 200) {
                var blob = xhr.response;
                var a = document.createElement("a");
                a.href = window.URL.createObjectURL(blob);
                a.download = d.fileName || "数据";
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(a.href);
            } else {
                layer.msg("下载失败：" + xhr.statusText, {icon:2})
            }
            
        }
    },
    obj: {
        copy: function (obj) {
            if (typeof (obj) == "object") {
                return JSON.parse(JSON.stringify(obj))
            } else {
                console.error("解析的参数非object,无法处理");
                return null;
            }
        },
        copyData: function (obj, target) { //从参数2中复制与参数1相同属性名的值
            var resObj = {};
            if (typeof obj == "object") {
                for (var key in obj) {
                    if (target[key] != undefined) {
                        resObj[key] = target[key];
                    } else {
                        resObj[key]=obj[key]
                    }
                }
                return resObj;
            }
        },
        find: function (obj, key, value) {
            if (typeof (obj) == "object" && obj.length > 0) {
                var arr = [];
                for (var i in obj) {
                    var o = obj[i];
                    if (o[key] == value) {
                        arr.push(o);
                    }
                }
                return arr;
                // return obj.filter((p) => { return p[key] == value })
            } else {
                console.error("解析的参数非object,无法处理");
                return null;
            }
        },
        toUrl: function (obj) {
            if (typeof (obj) != "object") {
                console.error("解析的参数非object,无法处理");
                return null;
            }
            var str = "";
            for (var key in obj) {
                if (obj[key] !== "") {
                    str += key + "=" + obj[key] + "&";
                }

            }
            return str.substring(0, str.length - 1);
        },
        isObj: function (obj) {
            console.log(typeof (obj))
            if (typeof (obj) == 'object') {
                return true;
            } else {
                return false;
            }
        },
        join: function (arr, str) {//去除空值后再join
            if (Array.isArray(arr)) {
                var obj = [];
                for (var i in arr) {
                    if (!LgString.IsNullOrEmpty(arr[i])) {
                        obj.push(arr[i]);
                    }
                }
                return obj.join(str);
            } else {
                console.error("arr非数组类型，无法执行");
                return null;
            }
        },
        group: function (obj, key) {//分组去重
            if (typeof (obj) == "object" && obj.length > 0) {
                var temp = {};
                var arr = [];
                for (var i in obj) {
                    var _obj = obj[i];
                    if (!temp[_obj[key]]) {
                        arr.push(_obj)
                    }
                    temp[_obj[key]] = "1";
                }
                return arr;
            } else {
                console.error("解析的参数非object,无法处理");
                return null;
            }
        }
    },
    convert: {
        toJson: function (data, errData) {
            var _data = errData
            try {
                var json = JSON.parse(data);
                if (json != null && json != undefined && typeof (json) == "object") {
                    _data = json;
                }
            }
            catch (e) {
                _data = errData;
            }
            return _data;
        },
        toString: function (data, errStr) {
            try {
                return JSON.stringify(data);
            }
            catch (e) {
                console.log(e)
                return errStr;
            }
        }
    },
    form: {
        data: {},
        errors: 0,
        render: function (d) {
            //清作所有已渲染的效果，避免重复渲染
            $(".renderItem").remove();
            var t = d.target;
            //渲染select
            if ($(t + " select").length > 0) {
                $(t + " select").each(function () {
                    var select = "<div class=\"renderSelect renderItem\" data-for=\"" + $(this).attr("name") + "\" ><ul>";
                    $(this).find("option").each(function () {
                        select += "<li data-val=\"" + $(this).val() + "\">" + $(this).text() + "</li>"
                    })
                    select += "</ul></div>";
                    $(this).hide().after(select)
                })
                //添加事件
                $(t).on("click", ".renderSelect li", function () {
                    var select = $(this).parents(".renderSelect").prev("select");
                    select.find("option[value=" + $(this).data("val") + "]").prop("selected", "selected");
                    $(this).addClass("selected").siblings("li").removeClass("selected")
                })
            }

            // 渲染单选框
            if ($(t + " input[type=radio]").length > 0) {
                $(t + " input[type=radio]").each(function () {
                    var radio = "<div class=\"renderRadio rendetItem\" data-for=\"" + $(this).attr("name") + "\" data-val=\"" + $(this).val() + "\"><i></i><span>" + $(this).attr("title") + "</span></div>";
                    $(this).hide().after(radio);
                })
                //绑定事件
                $(t).on("click", ".renderRadio", function () {
                    var val = $(this).data("val");
                    $(this).prev("input[type=radio]").prop("checked", "checked")
                })
            }
        },
        getData: function (d) {
            var t = $(d.target);
        },
        validate: function (d = { errClass: "reg-error", target:".lg-form"}) {
            var that = this;
            if (d.errClass == undefined) {
                d.errClass ='reg-error'
            }
            $(d.target + " .lg-form-reg").removeClass(d.errClass);
            this.errors = 0;
            $(d.target + " .lg-form-reg").each(function (i) {
                var value = undefined, reg = $(this).data("reg");
                switch (this.nodeName.toLowerCase()) {
                    case "select":
                        value = $(this).find("option:selected").val();
                        break;
                    case "input":
                        value = $(this).val();
                        break;
                }
                reg = reg.split("|")
                for (var i = 0; i < reg.length; i++) {
                    var b = lg.regx.test({
                        reg: reg[i],
                        val: value,
                        msg: ""
                    })
                    if (!b.state) {
                        that.errors++;
                        $(this).addClass(d.errClass);
                        if (typeof (d.fail) == "function") {
                            d.fail(this, b);
                        }
                        return false;
                    }
                }

            })
        }
    },
    regx: {
        test: function (d) {
            var result = { "state": true, "msg": "ok" };
            if (d == undefined) {
                console.log("验证参数为undefind");
                return result;
            }
            if (d.reg == undefined || d.reg == "") {
                return result;
            }
            switch (d.reg) {
                case "idCard":
                    var b = this.idCard(d.val);
                    if (!b) {
                        result.state = false;
                        if (d.msg != undefined && d.msg != "") {
                            result.msg = d.msg;
                        } else {
                            result.msg = "身份证格式有误!"
                        }
                    }
                    return result
                    break;
                case "phone":
                    var b = this.phone(d.val);
                    if (!b) {
                        result.state = false;
                        if (d.msg != undefined && d.msg != "") {
                            result.msg = d.msg;
                        } else {
                            result.msg = "手机号码格式有误!"
                        }
                    }
                    return result
                    break;
                case "number":
                    var b = this.number(d.val);
                    if (!b) {
                        result.state = false;
                        if (d.msg != undefined && d.msg != "") {
                            result.msg = d.msg;
                        } else {
                            result.msg = "此项只能填写数字!"
                        }
                    }
                    return result
                    break;
                case "required":
                    var b = this.required(d.val);
                    if (!b) {
                        result.state = false;
                        if (d.msg != undefined && d.msg != "") {
                            result.msg = d.msg;
                        } else {
                            result.msg = "必填项不可为空!"
                        }
                    }
                    return result
                    break;
                case "email":
                    var b = this.email(d.val);
                    if (!b) {
                        result.state = false;
                        if (d.msg != undefined && d.msg != "") {
                            result.msg = d.msg;
                        } else {
                            result.msg = "邮箱格式有误!"
                        }
                    }
                    return result
                    break;
                case 'password':
                    var b = this.password(d.val);
                    console.log(b);
                    if (!b) {
                        result.state = false;
                        if (d.msg != undefined && d.msg != "") {
                            result.msg = d.msg;
                        } else {
                            result.msg = "密码格式有误，必须包含数字、大小写字母、特殊字符且长度在8-30位之间";
                        }
                    }
                    return result;
                    break;

            }
        },
        idCard: function (idcode) {

            // 格式的正则
            // 正则思路
            /*
            第一位不可能是0
            第二位到第六位可以是0-9
            第七位到第十位是年份，所以七八位为19或者20
            十一位和十二位是月份，这两位是01-12之间的数值
            十三位和十四位是日期，是从01-31之间的数值
            十五，十六，十七都是数字0-9
            十八位可能是数字0-9，也可能是X
            */
            var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0-9]{2})([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;

            // 判断格式是否正确
            var format = idcard_patter.test(idcode);
            if (!format) {
                return false;
            }
            // 加权因子
            var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            // 校验码
            var check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
            var code = idcode + "";
            var last = idcode[17];//最后一位
            var seventeen = code.substring(0, 17);
            // ISO 7064:1983.MOD 11-2
            // 判断最后一位校验码是否正确
            var arr = seventeen.split("");
            var len = arr.length;
            var num = 0;
            for (var i = 0; i < len; i++) {
                num = num + arr[i] * weight_factor[i];
            }
            // 获取余数
            var resisue = num % 11;
            var last_no = check_code[resisue];

            // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
            return last === last_no && format ? true : false;
        },
        textRane: function (val, range) {
            if (val.trim()) {
                var b = true;
                if (parseInt(range[0]) > 0) {
                    b = val.length >= parseInt(range[0]);
                    if (!b) {
                        return false;
                    }
                }
                if (parseInt(range[1]) > 0) {
                    b = val.length <= parseInt(range[1])
                    if (!b) {
                        return false;
                    }
                }
                return b;
            } else {
                return false;
            }
            
        },
        phone: function (s) {
            var reg = /^1[3-9][0-9]{9}$/;
            return reg.test(s);
        },
        number: function (s) {
            var reg = /^[0-9]*(\.[0-9]*)?$/;
            return reg.test(s);
        },
        required: function (s) {
            s += "";
            return s.trim() != "";
        },
        email: function (s) {
            var reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
            return reg.test(s);
        },
        password: function (s) {
            var reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\s\S]{8,30}$/;
            return reg.test(s);
        }
    },
    string: {
        IsNullOrEmpty: function (str) {
            if (str == undefined || str == null || str == "") {
                return true;
            } else {
                return false;
            }
        },
        IsDate: function (str) {
            var regx = /^(\d{4})-(\d{2})-(\d{2})$/
            if (regx.test(str)) {
                return true
            } else {
                return false;
            }
        },
        PadLeft: function (str,n, char) {
            for (i = 0; i < n; i++) {
                str = char + str;
            }
            return str;
        }
    },
    page: function (d) {
        this.mounted = function () { };
        this.title = "";
        this.id = "";
        this.url = window.location.href;
        this.method = "get";
        this.data = {};
        this.time = "";
        this.target = "";
        this.laytable = null;
        this.vm = null;
        this.html = '';
        this.isCurr = false
        this.referrer = "";
        if (d) {
            //生命周期第一步，初始化属性
            for (var key in d) {
                if (key == "data" || key == "methods") {
                    for (var f in d[key]) {
                        this[f] = d[key][f]
                    }
                } else if (key == "mounted") {
                    this.mounted = d.mounted;
                }
            }
            
        } else {
            lg.log.error("未提供初始化参数！");
        } 
    },
    select:{
        fill: function (d) {
            if (d.data != undefined && d.data != null && d.data.length > 0) {
                for (var i = 0; i < d.data.length; i++) {
                    var data = d.data[i];
                    var o = "<option value=\"" + data[d.value] + "\">" + data[d.text] + "</option>";
                    $(d.target).append(o);
                }
                if (typeof (d.callback) == "function") {
                    d.callback();
                }
            }
        },
        reFill: function (d) {
            $(d.target).html("<option value=\"\">==请选择==</option>");
            if (d.state) {
                var data = d.data;
                if (data != null && data.length > 0) {
                    for (i = 0; i < data.length; i++) {
                        var o = "<option value=\"" + data[i].value + "\">" + data[i].text + "</option>";
                        $(d.target).append(o);
                    }
                    if (typeof (d.callback) == "function") {
                        d.callback();
                    }
                }
            }
        },
    },
    frame: function (d) {
        this.tabTitle = "#lg-frame-title";
        this.tabContent ="#lg-frame-content"
        this.data = {};
        this.temp = null;
        this.methods = {};
        this.methodType = "get";
        this.mounted = function () { };
        this.onLink = null;//当默认组件按钮 .lg-frame-link触发点击事件且执行默认逻辑后调用
        this.onPush = null;//添加新页面事件,返回添加后的页面对像
        this.onDestroyed = null;//移除页面之后的事件
        this.pages = [];
        this.curr = function () {
            if (this.pages && this.pages.length > 0) {
                return this.pages.filter(p => p.isCurr)[0];
            } else {
                return null;
            }
        };
        //初始化参数
        if (d && typeof d == "object") {
            if (d.data && typeof d.data == "object") {
                this.data = d.data;
            }
            if (d.tabTitle) {
                this.tabTitle = d.tabTitle
            }
            if (d.tabContent) {
                this.tabContent = d.tabContent;
            }
            if (d.methodType) {
                var type = d.methodType.toLowerCase();
                if (type == "get" || type == "post") {
                    this.methodType = type;
                } else {
                    console.error("methodType参数不合法！")
                }
            }
            if (d.methods && typeof d.methods == 'object') {
                for (let key in d.methods) {
                    if (typeof d.methods[key] == 'function') {
                        this[key] = d.methods[key];
                    } else {
                        console.error("属性：["+key+"]非有合法的function类型！")
                    }
                }
            }
            if (d.mounted && typeof d.mounted == "function") {
                this.mounted = d.mounted;
            }
            if (d.onPush && typeof d.onPush == "function") {
                this.onPush = d.onPush;
            }
            if (d.onDestroyed && typeof d.onDestroyed == "function") {
                this.onDestroyed = d.onDestroyed;
            }
            if (d.onLink && typeof d.onLink == "function") {
                this.onLink = d.onLink;
            }
        }
        //注册事件
        $("body").on("click", ".lg-frame-link", event => {
            var requestState = false;
            var type = $(event.currentTarget).attr("type");
            var obj = {
                title: $(event.currentTarget).attr("title")||"Page",
                url: $(event.currentTarget).attr("url")
            }
            if (obj.title && obj.url) {
                switch (type) {
                    case 'navigate':
                        requestState =this.NavigateTo(obj);
                        break;
                    case 'redirect':
                        requestState =this.RedirectTo(obj);
                        break;
                    default:
                        requestState =this.RedirectTo(obj);
                        break;
                }
            } else {
                lg.log.debug("缺少[title]或[url]属性！")
            }
            if (typeof this.onLink == "function") {
                this.onLink(event);
            }
        })
        $("body").on("click", this.tabTitle + " li", event => {
            this.SetCurr($(event.currentTarget).attr("url"))
        })
        //初始化完成后执行computed事件
        if (this.mounted && typeof (this.mounted) == "function") {
            this.mounted();
        }       
    },
    rsa: function (d) {
        this.pubkey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCs2Lu84tRrIiiPsmlgX1bFdvrmY2kn4+enMMpmdFdlNTvjSBMI3cu0uCj+wLvbXUl5Z9VHAJpB4IamMymA/d4cWcjvT2r08ESQ1q5BpB84tQ4qZQkI2wUlS5dqjKJPg6OPYIbZFXUfNaNp0wmrVAYt9zppNoyeiAX4fFJmGv+ypQIDAQAB";
        this.txt = JSON.stringify({
            Time: lg.GetDate("yyyy-MM-dd HH:mm:ss"),
            Token: lg.GetSN(32, 16),
        });
        if (d) {
            if (d.pubkey) {
                this.pubkey = d.pubkey;
            }
            if (d.txt) {
                this.txt = d.txt;
            }
        }
    },
    aes: function (d) {

    },
    GetSN: function (len, radix) {
        var chars =
            "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
        var uuid = [],
            i;
        radix = radix || chars.length;
        if (len) {
            // Compact form
            for (i = 0; i < len; i++) {
                let random = Math.random() * radix;
                uuid[i] = chars[0 | random];
            }
        } else {
            // rfc4122, version 4 form
            var r;

            // rfc4122 requires these characters
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
            uuid[14] = "4";

            // Fill in random data.  At i==19 set the high bits of clock sequence as
            // per rfc4122, sec. 4.1.5
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | (Math.random() * 16);
                    uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
                }
            }
        }

        return uuid.join("");
    },
    GetDate: function (format) {
        var myDate = new Date();
        var year = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
        var month = myDate.getMonth() + 1; //获取当前月份(0-11,0代表1月)
        var day = myDate.getDate(); //获取当前日(1-31)
        var hour = myDate.getHours(); //获取当前小时数(0-23)
        var minute = myDate.getMinutes(); //获取当前分钟数(0-59)
        var second = myDate.getSeconds(); //获取当前秒数(0-59)
        return format.replace("yyyy", year).replace("yy", year).replace("MM", month).replace("dd", day).replace("HH", hour).replace("mm", minute).replace("ss", second);
    },
    tpl:{
        tpls: new Array(),
        initTpl: function () {
            //var i = lgtpl.tpls.length - 1;
            $(".lgtpl").each(function () {
                lgtpl.tpls.push({ "tpl": $(this).html(), "target": $(this).data("target") });
                // i++;
            })
            $(".lgtpl").remove();
        },
        getTpl: function (t) {//根据选择器从模版容器中取出模版源码并返回
            var html = "";
            for (var i = 0; i < lgtpl.tpls.length; i++) {
                var p = lgtpl.tpls[i]
                if (p.target == t) {
                    html = p.tpl;
                }
            }
            return html;
        },
        getDataTpl: function (d, t) {//获取数据加载后的模版
            var tpl = lgtpl.getTpl(t);
            if (/{#for/g.test(tpl)) {
                tpl = lgtpl.processFor(d, tpl)
            }
            return tpl;

        },
        render: function (d, t) {
            if ($(t).length <= 0) { return }
            var tpl = lgtpl.getTpl(t);
            if (/{#for/g.test(tpl)) {
                tpl = lgtpl.processFor(d, tpl)
            }
            $(t).html(tpl)

        },
        renderItem: function (d, t) {
            if ($(t).length <= 0) { return }
            var html = "";
            for (var i = 0; i < lgtpl.tpls.length; i++) {
                var p = lgtpl.tpls[i]
                if (p.target == t) {
                    html = p.tpl;
                }
            }
            t = $(t);
            var item = html.match(/{@d\.(\w.+?)}/g);//接口返回的对像中的list
            for (var i = 0; i < item.length; i++) {
                var key = item[i].replace(/{@d\.(\w.+?)}/g, "$1")
                html = html.replace(item[i], d[key])
            }
            t.html("").html(html);
        },
        renderList: function (d, t) {//取模版源码，正则找出源码中的关键词，用关键词读取list中对应名称的属性值替换之
            if ($(t).length <= 0) { return }
            var tpl = "";
            for (var i = 0; i < lgtpl.tpls.length; i++) {
                var p = lgtpl.tpls[i]
                if (p.target == t) {
                    tpl = p.tpl;
                }
            }
            t = $(t);
            var list = tpl.match(/{@list\.(\w.+?)}/g);//接口返回的对像
            var html = "";
            for (var i = 0; i < d.length; i++) {
                var data = d[i];
                html += tpl;
                for (var j = 0; j < list.length; j++) {
                    var key = list[j].replace(/{@list\.(\w.+?)}/g, "$1")
                    html = html.replace(list[j], data[key])
                }
            }
            t.html("").html(html);
        },
        processFor: function (d, tpl) {//d为数据源，t为待处理的tpl
            var regx = /({#for:data=")(.+)"}([\s\S]*)({#endfor})/g
            var _forStr = (tpl.match(regx))[0];
            var _tpl = _forStr.replace(regx, "$3")
            var _dataStr = _forStr.replace(regx, "$2")
            var _data = eval(_dataStr)
            var _listParam = _tpl.match(/{@list\.(\w.+?)}/g)
            var _html = "";
            for (var i = 0; i < _data.length; i++) {
                _html += _tpl;
                var list = _data[i];
                for (var j = 0; j < _listParam.length; j++) {
                    var key = _listParam[j].replace(/{@list\.(\w.+?)}/g, "$1")
                    _html = _html.replace(_listParam[j], list[key])
                }
            }
            tpl = tpl.replace(regx, _html)
            return tpl
        }
    }
}
//pages对像元数据
lg.frame.prototype.createPage = function (d) {
    var page = new lg.page(d);
    if (this.temp) {
        page.id = this.temp.id;
        page.title = this.temp.title;
        page.url = this.temp.url;
        page.html = this.temp.html;
        page.referrer = this.temp.referrer || "";
    }   
    this.pages.push(page);
    this.SetCurr(page.url);
    this.temp = null;
    return page;
}
lg.frame.prototype.GetPage = function (key,val) {
    var obj = { index: -1, page: null };
    for (let i in this.pages) {
        if (this.pages[i][key] == val) {
            obj.index = i;
            obj.page = this.pages[i]
            break;
        }
    }
    return obj;
}
lg.frame.prototype.Push = function (page) {
    if (page) {
        var arr = this.pages.filter(p => p.id == page.id);
        if (arr && arr[0]) {
            return arr[0]
        } else {
            this.pages.push(page);
            return this.pages[this.pages.length-1]
        }
        if (typeof this.onPush == "function") {
            this.onPush(this.pages[this.pages.length - 1]);
        }
    }
}
lg.frame.prototype.Destroy = function (url) {
    let index = -1;
    for (let i in this.pages) {
        if (this.pages[i].url == url) {
            index = i;
        }
    }
    this.pages.splice(index, 1);
    if (typeof this.onDestroyed == "function") {
        this.onDestroyed();
    }
}
lg.frame.prototype.SetCurr = function (url) {
    for (let i in this.pages) {
        if (this.pages[i].url == url) {
            this.pages[i].isCurr = true;
        } else {
            this.pages[i].isCurr = false;
        }
    }
}
lg.frame.prototype.NavigateTo = function (d) {
    var requestState = true;
    if (d.url) {
        var arr = this.pages.filter(p => p.url == d.url);
        if (arr && arr.length > 0) {
            this.ChangePage(d.url);
        } else {
            var loader = layer.load(1, {
                shade: [0.1, '#000'] //0.1透明度的白色背景
            });
            $.ajax({
                url: d.url,
                type: this.methodType,
                success: res => {
                    layer.close(loader);
                    var json = lg.convert.toJson(res, false)
                    if (!json) {
                        //this.pages.push(page)
                        //this.SetCurr(page.id);
                        this.temp = {
                            id: "lg" + Date.parse(new Date()).toString() + (this.pages.length + 1),
                            title: d.title,
                            html: res,
                            url: d.url,
                            referrer: this.pages.length > 0 ? this.curr().url : ""
                        }
                        if (typeof d.success == "function") {
                            d.success(page);
                        } else {
                            $(this.tabTitle).append("<li url='" + this.temp.url + "'>" + this.temp.title + "</li>");
                            $(this.tabContent).append("<div class='layui-tab-item' id='" + this.temp.id + "'>" + this.temp.html + "</div>")
                            $(this.tabTitle + " li").last().trigger("click");
                        }
                    }
                    else {
                        requestState = false;
                        if (json.code == 110) {
                            top.location.href = "/Lgm/Login"
                        } else {
                            layer.msg(json.msg, { icon: 2 })
                        }

                    }
                },
                error: function (err) {
                    requestState = false;
                    layer.close(loader);
                    layer.msg("数据请求异常！", { icon: 2 })
                }
            });
        }
    } else {
        requestState = false;
        layer.msg("确少主要参数URL！", {icon:2})
    }
    return requestState;
}
lg.frame.prototype.RedirectTo = function (d) {
    var requestState = true;
    if (d.url) {
        var loader = layer.load(1, {
            shade: [0.1, '#000'] //0.1透明度的白色背景
        });
        $.ajax({
            url: d.url,
            type: this.methodType,
            success: res => {
                layer.close(loader);
                var json = lg.convert.toJson(res, false)
                if (!json) {
                    this.pages = [];
                    $(this.tabTitle).html("");
                    $(this.tabContent).html("");
                    this.temp = {
                        id: "lg" + Date.parse(new Date()).toString() + (this.pages.length + 1),
                        title: d.title,
                        html: res,
                        url: d.url,
                        referrer: this.pages.length > 0 ? this.curr().url : ""
                    }
                    if (typeof d.success == "function") {
                        d.success(page);
                    } else {
                        $(this.tabTitle).append("<li url='" + this.temp.url + "'>" + this.temp.title + "</li>");
                        $(this.tabContent).append("<div class='layui-tab-item' id='" + this.temp.id + "'>" + this.temp.html + "</div>")
                        $(this.tabTitle + " li").last().trigger("click");
                    }
                }
                else {
                    requestState = false;
                    if (json.code == 110) {
                        top.location.href = "/Lgm/Login"
                    } else {
                        layer.msg(json.msg, { icon: 2 })
                    }
                }
                return requestState;
            },
            error: function (err) {
               
                layer.close(loader);
                layer.msg("数据请求异常！", { icon: 2 })
                return false;
            }
        });
    } else {
        return false;
        layer.msg("确少主要参数URL！", { icon: 2 })
    }
}
lg.frame.prototype.ChangePage = function (url) {
    var that = this;
    this.SetCurr(url);
    $(this.tabTitle+" li").each(function () {
        var _url = $(this).attr("url");
        if (url == _url) {
            $(this).trigger("click");
        }
    })

}
lg.frame.prototype.Back = function (url,success) {
    var obj = this.GetPage("url",url); 
    if (obj.index > -1) {
        this.pages.splice(obj.index, 1)
        $(this.tabTitle + " .layui-this").remove();
        $(this.tabContent + " .layui-show").remove();
        this.ChangePage(obj.page.referrer);
        if (typeof success == "function") {
            success(this.curr());
        }
    }   
}
lg.page.prototype.mount = function () {
    if (this.mounted && typeof (this.mounted) == "function") {
        this.mounted();
    }
};
lg.rsa.prototype.encrypt = function () {
    var rsa = new JSEncrypt();
    rsa.setPublicKey(this.pubkey);
    return rsa.encrypt(this.txt)
}

